/**
 * Created by Administrator on 2016/6/25.
 */
require.config({
    baseUrl:PUBLIC + "/Admin/js/lib"
});
define(function(require){
    var $ = require('jquery');
    require('jquery.form');
    require('tips/msgbox');
    window.$ = window.jQuery = $;
    var c=require('../common');
    var dialog = require('bDialog/dialog');
    window.dialog=dialog;
    require('datetimepicker/datetimepicker');
    require('select');
    require('webui');

    $(function() {
        //################商品管理
        //日期时间选择器
        $('#start_time').datetimepicker({
            format:'Y-m-d H:i:s',
            onShow:function( ct ){
                var end_time = $('#end_time').val();
                this.setOptions({
                    maxDate:end_time?new Date(Date.parse(end_time.replace(/-/g,   "/"))):false
                })
            },
            closeOnDateSelect:true,
            timepicker:false
        });

        $('#end_time').datetimepicker({
            format:'Y-m-d H:i:s',
            onShow:function( ct ){
                var start_time = $('#start_time').val();
                this.setOptions({
                    minDate:start_time?new Date(Date.parse(start_time.replace(/-/g,   "/"))):false
                })
            },
            closeOnDateSelect:true,
            timepicker:false
        });
        
        //排序
        $('#sort').selectbox({
            callback:function(v){
                $('input[name="sort"]').val(v.attr('v'));
                $('#pro_search_submit').click();
            }
        });

        $('#cid').selectbox({w:175});//选择商品分类

        //选择所属店铺
        $('#shop_id').selectbox({w:175,callback:function (v){
            var selVal = v.attr('v');
            if(!empty(selVal)){
                $.get(URL+"/getProductCateList?sid="+selVal,function(data){
                   if(data.status == 1){
                       $('#cid').html(data.data['html']);
                       $('#cid_ul').html(data.data['str']);
                   }else{
                       c.error(data.info,2000);
                   }
                    return true;
                });
            }
        }});

        //搜索展开、关闭
        $('.search_customer,.search,.cancel_search,#index_search_form,#promote_search_form').click(function(){
            $('#search_form')[0].reset();
            $('#search_form').slideToggle('fast');
        });
        $('[name="sell_num"],[name="price"]').click(function(){
            if($(this).val()=='3'){
                $(this).parent().siblings('.custom').show();
            }else{
                $(this).parent().siblings('.custom').hide();
            }
        });

        $('#pro_search_submit').click(function(){
            if($('[name="price"]:checked').val()=='3'){
                if($('[name="price_start"]').val()=='' || $('[name="price_end"]').val()==''){
                    c.error('请入商品价格区间值',2000)
                    return false;
                }
            }else if($('[name="sell_num"]:checked').val()=='3'){
                if($('[name="sell_num_start"]').val()=='' || $('[name="sell_num_end"]').val()==''){
                    c.error('请入商品销量区间值',2000)
                    return false;
                }
            }
        });

        /**
         * 商品列表 操作
         */
        $('select[name="pro_operate"]').selectbox({callback:function(v){
            var selVal = v.attr('v');
            var valArr = selVal.split(',');
            var id = valArr[1];

            if(valArr[0]==1){ //编辑
                location.href = URL+'/edit?id='+id;
            }else if(valArr[0]==3){ //上架
                $.post(URL+'/putaway',{'id':id},function(data){
                    if(data.status == 1){
                        ZENG.msgbox.show(data.info, 4,1000);
                        setTimeout(function(){location.reload()},1000);
                    }else{
                        ZENG.msgbox.show(data.info, 5,2000);
                    }
                },'json');
            }else if(valArr[0]==2){ //下架
                dialog({title:'系统提示',content:'<div style="font-size:16px;padding:20px">确定要下架此商品？</div>',ok:function(){
                    var d = dialog({title:'下架理由',content:'<textarea name="con" maxlength="200" style="width:300px;height:100px"></textarea>',ok:function(){
                        var reason = $('[name="con"]').val();
                        if(reason==''){
                            ZENG.msgbox.show('下架理由不能为空', 5,2000);
                            return false;
                        }else{
                            $.post(URL+'/soldOut',{'id':id,'reason':reason},function(data){
                                if(data.status == 1){
                                    ZENG.msgbox.show(data.info, 4,1000);
                                    setTimeout(function(){location.reload()},1000);
                                }else{
                                    ZENG.msgbox.show(data.info, 5,2000);
                                }
                            },'json');
                        }
                    },cancel:function(){},okVal:'确定',cancelVal:'取消'});
                },cancel:function(){},okVal:'确定',cancelVal:'取消'});

            } else if(valArr[0]==4){//查看订单
                location.href = URL+'/orderList?id='+id;
            }
        }});

        $('#price,input[name="spec_price[]"]').off().on('blur keyup paste',function(){
            var eb = $.trim($(this).val());

            if(!/^\d*(\.\d{0,2})?$/.test(eb)){
                $(this).val('');
            }
        });

        //是否分期
        $('input[name="has_attr"]').click(function () {
            if(this.value==1){
                $('dl.spec').removeClass('hidden');
            } else {
                
                $('dl.spec').removeClass('hidden').addClass('hidden');
            }
        });

        $('dl.instalment input[name="instalment[]"]').click(function () {
            if(!this.checked){
                if($('dl.instalment input[name="instalment[]"]:checked').length==0){
                    
                    $('dl.instalment').removeClass('hidden').addClass('hidden');
                }
            }
        });

        //增加，删除规格
        $('.seritem').delegate('.step li .delete', 'click', function(event) {
            $(this).parents('li').fadeOut(function(){$(this).remove();});
        });
        $('.seritem').delegate('.field .add ', 'click', function(event) {
            var li='<li>'
                +'    <input name="spec_key[]" type="hidden" readonly value="" />'
                +'    <span class="tm">名称(容量)：</span>'
                +'    <input name="spec_name[]" type="text" maxlength="5" class="tb" value="">'
                +'    <span class="tm">价格：</span>'
                +'    <input name="spec_price[]" type="text" maxlength="10" class="tb" value="">'
                //+'    <span class="tm">库存：</span>'
                //+'    <input type="text" name="spec_store[]" maxlength="10" onafterpaste="this.value=this.value.replace(/\D/g,\'\');" onkeyup="this.value=this.value.replace(/\D/g,\'\');" class="tb" value="" />'
                +'    <span class="tm">单位：</span>'
                +'    <input name="spec_unit[]" type="text" maxlength="10" class="tb" value="">'
                +'    <a class="btn btn-default delete">删除</a>'
                +'</li>';
            $(this).parents('.field').find('.step').append(li);
        });


        if($('.fileupload').length){
            require(['fileupload/fupload'],function () {
                $('.fileupload').each(function () {
                    var fileuploadObj = $(this);
                    var uid = fileuploadObj.closest('.upload-area').find('.uid').val();
                    var role = fileuploadObj.closest('.upload-area').find('.role').val();
                    var path = fileuploadObj.closest('.upload-area').find('.upload_path').val();
                    var field = fileuploadObj.closest('.upload-area').find('.input_field').val();
                    var maxNum = fileuploadObj.closest('.upload-area').find('.maxNum').val();
                    var icoh = 0;
                    if(maxNum > 1){
                        icoh = 1;
                    }

                    fileuploadObj.fupload({path: path, operator:'manage',uid:uid,role:role,input: field, max: maxNum,imgType:'big',icoh:icoh});
                });
            });
        }

        //表单提交
        $('#product_edit_form').ajaxForm({
            beforeSubmit:  checkForm,  // pre-submit callback
            success:       complete,  // post-submit callback
            dataType: 'json'
        });

        function checkForm(){
            /*var has_attr = parseInt($('input[name="has_attr"]:checked').val());

            if(has_attr == 1){
                var store = parseInt($.trim($('#store').val()));
                var specStore = 0;
                $('.seritem .step li').each(function () {
                    specStore += parseInt($.trim($(this).find('input[name="spec_store[]"]').val()));
                });

                if(store != specStore){
                    c.error('库存总数与规格库存之和不匹配',2000);
                    return false;
                }
            }*/
            
            return true;
        }

        function complete(data){
            if (data.status==1){
                c.success(data.info,1000);
                setTimeout(function(){
                    location.href=URL+'/index';
                },1500);
            }else{
                c.error(data.info,2000);
                return false;
            }
        }
        
        //#######商品分类管理

        //删除
        $('table .del').off().on('click', function () {
            var id = $(this).data('id');
            if (empty(id)) {
                c.error('请选择操作项！', 2000);
                return false;
            }

            dialog({
                title: '温馨提示', height: 100, icon: 'warning', content: '是否确定删除？', ok: function () {
                    $.post(URL + '/del', {id:id}, function (data) {
                        if (data.status == 1) {
                            c.success(data.info, 1000);
                            setTimeout(function () {
                                location.reload();
                            }, 1500);
                            return true;
                        } else {
                            c.error(data.info, 2000);
                            return false;
                        }
                    }, 'json');
                },
                cancel: function () {
                },
                okVal: '确定', cancelVal: '取消'
            });
        });


        //添加、编辑商品分类
        $('.so_main').delegate('.add_cate,.edit_cate','click',function(){
            var t = $(this);
            var dialogTitle = '添加商品分类';
            var url = URL+'/edit';
            var id = 0;
            if(t.hasClass('edit_cate')){
                id = t.data('id');
                dialogTitle = '编辑商品分类';
                url += '?id=' + id;
            }
            var d = dialog({title:dialogTitle,width:400,url:url,end:function(){
                $('#shop_sel').selectbox();
            },ok:function(){
                var body = this.c('body');
                var title = $.trim(body.find('input[name="title"]').val());
                var sort = $.trim(body.find('input[name="sort"]').val());
                var shop_id = $('#shop_sel').val();

                if(empty(title)){
                    c.error('请输入分类名称!',2000);
                    $('input[name="title"]').focus();
                    return false;
                }
                if(empty(shop_id)){
                    c.error('请选择所属分店!',2000);
                    return false;
                }
                
                $.post(URL+'/update',{title:title,id:id,sort:sort,'shop_id':shop_id},function(msg){
                    if(msg.status == 1) {
                        c.success(msg.info,1000,function(){
                            location.reload();
                        });
                        return true;
                    } else {
                        c.error(msg.info,2000);
                        return false;
                    }
                });
                return false;
            },cancel:function(){},okVal:'保存',cancelVal:'取消'});
            return false;
        });

        //排序
        $('.sorts').off().on('blur',function(){
            var id = $(this).closest('tr').data('id');
            var sort = parseInt($(this).val());
            var origin = parseInt($(this).data('origin'));

            if(origin!=sort){
                var forms = {};
                forms['id'] = id;
                forms['sort'] = sort;

                $.post(URL+'/sort',forms,function(data){
                    if(data.status==1){
                        c.success(data.info,1000);
                        setTimeout(function(){
                            location.reload();
                        },1500);
                    } else {
                        c.error(data.info,2000);
                        return false;
                    }
                },'json');
            }
        });
    })
});